package com.zscat.mallplus.qsg.contrller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zscat.mallplus.annotation.SysLog;
import com.zscat.mallplus.qsg.Certificate;
import com.zscat.mallplus.qsg.QsgHexiao;
import com.zscat.mallplus.qsg.service.CertificateService;
import com.zscat.mallplus.qsg.service.IQsgHexiaoService;
import com.zscat.mallplus.util.UserUtils;
import com.zscat.mallplus.utils.CommonResult;
import com.zscat.mallplus.utils.ValidatorUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@Api(tags = "HexiaoController", description = "券管理")
@RequestMapping("/qsg/certificate")
public class CertificateController {

    @Autowired
    private CertificateService certificateService;

    @SysLog(MODULE = "qsg", REMARK = "根据条件查询所有券列表")
    @ApiOperation("根据条件查询所有券列表")
    @GetMapping(value = "/list")
    public Object getCertByPage(@RequestParam(required = false) String phone, @RequestParam(required = false) String code,
                                @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                @RequestParam(value = "pageSize", defaultValue = "30") Integer pageSize
    ) {
        QueryWrapper qw = new QueryWrapper();
        qw.orderByDesc("create_datetime");
        qw.eq("store_id", UserUtils.getCurrentMember().getQsgStoreId());
        if (StringUtils.isNotBlank(phone)) {
            qw.like("member_phone", phone);
        }
        if (StringUtils.isNotBlank(code)) {
            qw.like("source_code", code);
        }
        try {
            IPage<Certificate> certificateIPage = certificateService.page(new Page<>(pageNum, pageSize), qw);
            return new CommonResult().success(certificateIPage);
        } catch (Exception e) {
            log.error("根据条件查询所有券列表：%s", e.getMessage(), e);
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "qsg", REMARK = "删除券表")
    @ApiOperation("删除券表")
    @PostMapping(value = "/delete/{id}")
    public Object deleteDevice(@ApiParam("券表id") @PathVariable Long id) {
        try {
            if (ValidatorUtils.empty(id)) {
                return new CommonResult().paramFailed("券表id");
            }
            if (certificateService.removeById(id)) {
                return new CommonResult().success();
            }
        } catch (Exception e) {
            log.error("删除券表：%s", e.getMessage(), e);
            return new CommonResult().failed();
        }
        return new CommonResult().failed();
    }
}
